package littlewhisker.managers {
	import flash.display.Sprite;
	import flash.utils.Dictionary;
	import flash.display.MovieClip;
	import flash.display.LoaderInfo;
	import flash.media.Sound;
	import flash.display.BitmapData;

	/**
	 * @author Philip
	 */
	public class AssetManager {
		
		private static var assetLibraries:Dictionary;
		private static var swfLibrary:Dictionary;
		private static var xmlLibrary:Dictionary;
		
		public static function addXML(xml:XML, xmlID:String):void{
			if(!xmlLibrary) xmlLibrary = new Dictionary(true);
			xmlLibrary[xmlID] = xml;
		}
		
		public static function addLibrary(swf : Sprite, libraryID:String) : void {
			if(!assetLibraries) assetLibraries = new Dictionary(true);
			assetLibraries[libraryID] = swf.loaderInfo;
			if(!swfLibrary) swfLibrary = new Dictionary(true);
			swfLibrary[libraryID] = swf;
		}
		
		public static function removeLibrary(libraryID:String) : void {
			delete assetLibraries[libraryID];
		}
		
		public static function getSWF(id:String):Sprite{
			return swfLibrary[id] as Sprite;
		}
		
		public static function getMovieClip(id:String, library:String = null) : MovieClip {  
            var c:Class = getAsset(id,library);
			return new c() as MovieClip;
        }
        
        public static function getBitmap(id:String, library:String = null) : BitmapData {  
			var c:Class = getAsset(id,library);
             return new c(null, null) as BitmapData;  
        }
        
        public static function getSound(id:String, library:String = null) : Sound {  
			var c:Class = getAsset(id,library);
            return Sound(new c());  
        } 
        
        private static function getAsset(id:String,library:String = null):Class{
        	var c:Class;
        	if(library){
        		c = (assetLibraries[library] as LoaderInfo).applicationDomain.getDefinition(id) as Class;  
        	} else {
        		c = searchassetLibraries(id);
        	}
        	return c;
        }
        
        private static function searchassetLibraries(id:String):Class{
        	var c:Class;
       
        	for each (var value:LoaderInfo in assetLibraries) {
	  			if(value.applicationDomain.getDefinition(id)){
	  				c = value.applicationDomain.getDefinition(id) as Class;
	  				return c;
	  			} 
	  		}
        	return null;
        }
        
       	public static function getXML(id:String):XML{
			return xmlLibrary[id];
		}
	}
}
